package com.easyhuan.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyhuan.pojo.Goods;
import com.easyhuan.pojo.PageInfo;
import com.easyhuan.pojo.User;
import com.easyhuan.util.HibernateUtil;

public class GoodsUtil {

	// 删除单个商品
	public boolean deleteGoods(Session session, Transaction trans, Goods goods) {
		try {
			trans.begin();
			session.delete(goods);
			trans.commit();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}

	// 删除多个商品
	public boolean deleteGoodsList(Session session, Transaction trans,
			List<Goods> list) {
		try {
			trans.begin();
			for (Goods goods : list) {
				session.delete(goods);
			}
			trans.commit();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	// 修改商品
	public static boolean updatePojo(Session session, Transaction trans,
			Goods goods) {
		try {
			trans.begin();
			session.update(goods);
			trans.commit();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}

	// 根据Id查询商品信息
	public Goods selectGoodsById(Session session, String id) {
		String hql = "FROM Goods WHERE goodsId = ?";
		Integer Id = Integer.parseInt(id);
		Query query = session.createQuery(hql);
		query.setInteger(0, Id);
		Goods goods = (Goods) query.uniqueResult();
		return goods;
	}

	// 分页查询商品()
	public List<Goods> selectGoodsWithPage(User user, PageInfo page) {
		Session session = HibernateUtil.getHibernateSession();
		String hql = "FROM Goods g WHERE g.user.userId = ?";
		Query query = session.createQuery(hql);
		int MAX_RESULT = page.getShowNumber();
		int start = page.getStart();
		query.setFirstResult(start);
		query.setMaxResults(MAX_RESULT);
		query.setEntity(0, user);
		List<Goods> list = query.list();
		session.close();
		return list;
	}

	// 分页查询商品（带查询条件）
	public List<Goods> selectGoodsWithCondition(String condition, int currPage,
			int MAX_RESULT) {

		return null;
	}

	public String getHQL(String goodsItem, String condition) {
		String hql = "FROM Goods WHERE " + goodsItem + " like '%" + condition
				+ "%'";
		return hql;
	}

	// 获取在特定条件下的记录条数
	public Long getResultCount(String tableName,String where) throws Exception {
		Session session = HibernateUtil.getHibernateSession();
		Long resultCount = (Long) session.createQuery(
				"SELECT count(*) FROM " + tableName + " p "+where).uniqueResult();
		session.close();
		return resultCount;
	}
}
